/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.factory.ConstantFactory;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.util.FilePortUtil;
import cn.emove.modular.system.model.MeterReadingDto;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.MeterTemplateService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.MeterReadingHandleWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 抄表模板
 *
 * @author JJX
 */
@Controller
@RequestMapping("/meterTemplate")
public class MeterTemplateController extends BaseController {

    private static String PREFIX = "/modular/system/meter/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private MeterTemplateService meterTemplateService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;


    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "meterTemplate.html";
    }

    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String monthTime,
                       @RequestParam(required = false) String meterModel) {


        //拼接查询条件
        if (ToolUtil.isNotEmpty(monthTime)) {
            monthTime = monthTime.replace("-", "");

        }
        Page<Map<String, Object>> meterTemplates = meterTemplateService.selectMeterTemplates(null, monthTime,meterModel);
        Page wrapped = new MeterReadingHandleWrapper(meterTemplates).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }


    /**
     * 导出报表
     *
     * @return
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(@RequestParam(required = false) String monthTime,@RequestParam(required = false) String ids,@RequestParam(required = false) String meterModel, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ids = ids.substring(0,ids.lastIndexOf(","));
        //拼接查询条件
        if (ToolUtil.isNotEmpty(monthTime)) {
            monthTime = monthTime.replace("-", "");

        }
        String[] array = ids.split(",");
        //获取数据
        List<MeterReadingDto> list = meterTemplateService.selectAllMeterTemplates(monthTime,array,meterModel);

        //excel标题
        String[] title = {"所属月份", "铺位号", "品牌名称", "合同编号",  "能源表类型", "能源表编号","能源表模式", "起码", "止码"};

        //excel文件名
        String fileName = "抄表模板.xls";

        //sheet名
        String sheetName = "抄表模板";

        String[][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            MeterReadingDto obj = list.get(i);
            content[i][0] = obj.getMeterRedingMonth();
            content[i][1] = obj.getShopAdr();
            content[i][2] = obj.getShopName();
            content[i][3] = obj.getContractCode();
            content[i][4] = ConstantFactory.me().getMeterName(obj.getMeterType().toString());
            content[i][5] = obj.getMeterNo();
            content[i][6] = ConstantFactory.me().getMeterModelName(obj.getMeterModel());
            content[i][7] = obj.getStartMum();
        }

//创建HSSFWorkbook
        HSSFWorkbook wb = FilePortUtil.getHSSFWorkbook(sheetName, title, content, null);

//响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
